package com.hbnu.thread;

import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo5 implements Runnable {
    private Integer ticket = 20;

//    @Override
//    public void run() {
//        while(ticket > 0){
//            try {
//                Thread.sleep(10);
//                System.out.println(Thread.currentThread().getName()+"卖出了"+ticket--+"号票");
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }


//    @Override
//    public synchronized void run(){
//
//        //也可以将锁放在代码块
//        while(ticket > 0){
//            try {
//                Thread.sleep(10);
//                System.out.println(Thread.currentThread().getName()+"卖出了"+ticket--+"号票");
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }


//    @Override
//    public void run(){
//        synchronized (this){        //同步代码块
//
//        //也可以将锁放在代码块
//            while(ticket > 0){
//                try {
//                    Thread.sleep(10);
//                    System.out.println(Thread.currentThread().getName()+"卖出了"+ticket--+"号票");
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        }
//        try {
//            Thread.sleep(200);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//    }


    private ReentrantLock lock = new ReentrantLock();

    @Override
    public synchronized void run() {

        //也可以将锁放在代码块

        while (ticket >= 0) {
            lock.lock();
            try {
                Thread.sleep(10);
                System.out.println(Thread.currentThread().getName() + "卖出了" + ticket-- + "号票");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}